package com.code.exam.service.impl;


import com.code.exam.dto.AdminLoginDTO;
import com.code.exam.dto.CgPasswordDTO;
import com.code.exam.entity.Admin;
import com.code.exam.entity.CgPassword;
import com.code.exam.entity.User;
import com.code.exam.mapper.AdminMapper;
import com.code.exam.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;


    /**
     * 管理员登录
     *
     * @param adminLoginDTO
     * @return
     */
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        Admin admin = adminMapper.getByUsername(username);

        //处理异常状况（密码错误，用户不存在）
        if(admin == null){
            //用户不存在
            throw new RuntimeException("用户不存在");
        }
        if(!admin.getPassword().equals(password)){
            //密码错误
            throw new RuntimeException("密码错误");
        }

        //返回实体对象
        return admin;
    }


    public String register(Admin admin){
        String adminName = admin.getUsername();
        Admin admin1 = adminMapper.getByUsername(adminName);
        if(admin1 != null){
            throw new RuntimeException("用户名已存在");
        }
        else{
              adminMapper.register(admin);
        }
        return adminName;
    }


    public void changepassword(Long adminId, CgPasswordDTO cgPasswordDTO){
        User admin = adminMapper.getById(adminId);
        CgPassword cgPassword = new CgPassword();
        BeanUtils.copyProperties(cgPasswordDTO,cgPassword);
        if(! cgPassword.getOldPassword().equals(admin.getPassword())){
            new RuntimeException("旧密码错误");
        }
        else{
            adminMapper.changepassword(cgPassword.getNewPassword(),adminId);
        }

    }
}
